//
//  FSWCustomRefresh.m
//  TuanLife
//
//  Created by 伏圣文 on 2017/12/27.
//  Copyright © 2017年 HuiNaMac. All rights reserved.
//

#import "FSWCustomRefresh.h"

#define LINESPACE 4

@interface FSWCustomRefresGifhHeader()

@property (strong, nonatomic) UILabel *updateStatusLabel;
@property (strong, nonatomic) UIImageView *refreshImageView;
@property (copy, nonatomic) NSString* timeStatus;
@property (nonatomic,strong) NSMutableArray *refreshImages;/** <刷新动画的图片数组 */
@property (nonatomic,strong) NSMutableArray *refreshDownImages;/** <刷新动画的图片数组 */
@end
@implementation FSWCustomRefresGifhHeader

- (instancetype)init{
    if (self = [super init]) {
        //        self.timeStatus = [XCCustomRefreshHeader compareCurrentTime:[[NSUserDefaults standardUserDefaults] objectForKey:@"currenttime"]];
    }
    return self;
}

- (void)prepare
{
    [super prepare];
    XCLog(@"%@",self.scrollView);
    [self configUI];
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState;
    switch (state) {
        case MJRefreshStateIdle:{
            self.updateStatusLabel.text = [NSString stringWithFormat:@"最后更新：%@",self.timeStatus];
            [self changeLineSpace];
            break;
        }
        case MJRefreshStatePulling:{
            self.updateStatusLabel.text = [NSString stringWithFormat:@"最后更新：%@",self.timeStatus];
            [self changeLineSpace];
            break;
        }
        case MJRefreshStateRefreshing:{
            self.refreshImageView.animationImages = self.refreshImages;
            self.refreshImageView.animationDuration = 1;
            [self.refreshImageView startAnimating];
            self.updateStatusLabel.text = [NSString stringWithFormat:@"最后更新：%@",self.timeStatus];
            [self changeLineSpace];
            [self storeCurrentTimeDate];
            break;
        }
        default:
            break;
    }
}

- (void)setPullingPercent:(CGFloat)pullingPercent
{
    [super setPullingPercent:pullingPercent];
    if (self.state != MJRefreshStateIdle || self.refreshDownImages.count == 0) return;
    [self.refreshImageView stopAnimating];
    
    NSUInteger index =  self.refreshDownImages.count * pullingPercent;
    if (index >= self.refreshDownImages.count) index = self.refreshDownImages.count - 1;
    self.refreshImageView.image = self.refreshDownImages[index];
}

- (void)scrollViewPanStateDidChange:(NSDictionary *)change
{
    [super scrollViewPanStateDidChange:change];
    self.timeStatus = [FSWCustomRefresGifhHeader compareCurrentTime:[[NSUserDefaults standardUserDefaults] objectForKey:@"currenttime"]];
}

- (void)placeSubviews
{
    [super placeSubviews];
    
    switch (self.scrollView.tag) {
        case 10001:
            self.refreshImageView.frame = CGRectMake(self.bounds.size.width / 2-13, 10, 26, 26);
            break;
        default:
            self.refreshImageView.frame = CGRectMake(self.bounds.size.width / 2-13, 10, 26, 26);
            break;
    }
    self.updateStatusLabel.frame = CGRectMake(self.bounds.size.width / 2 - 150, self.refreshImageView.mj_h +15, 300, 20);
}

#pragma mark --Private
+ (NSString *) compareCurrentTime:(NSDate*) compareDate
{
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }else if((temp = timeInterval/60) <60) {
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }else if((temp = temp/60) <24) {
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }else if((temp = temp/24) < 2) {
        result = @"昨天";
    }else {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
        NSString *strDate = [dateFormatter stringFromDate:compareDate];
        result = strDate;
    }
    return  result;
}

- (void)storeCurrentTimeDate
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate dateWithTimeIntervalSinceNow:0] forKey:@"currenttime"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)changeLineSpace
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.updateStatusLabel.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    [paragraphStyle setLineSpacing:LINESPACE];
    
    //    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.updateStatusLabel.text length])];
    self.updateStatusLabel.attributedText = attributedString;
    [self.updateStatusLabel sizeToFit];
}

- (void)configUI
{
    self.mj_h = 70;
    
    self.updateStatusLabel = [[UILabel alloc] init];
    self.updateStatusLabel.textColor = [UIColor colorWithRed:12/255.0 green:36/255.0 blue:56/255.0 alpha:1];
    self.updateStatusLabel.font = [UIFont fontWithName:@"Heiti SC" size:14];
    self.updateStatusLabel.textAlignment = NSTextAlignmentCenter;
    self.updateStatusLabel.numberOfLines = 2;
    self.updateStatusLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:self.updateStatusLabel];
    
    self.refreshImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"001"]];
    self.refreshImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.refreshImageView];
    
    self.updateStatusLabel.hidden = NO;
    self.lastUpdatedTimeLabel.hidden = NO;
    self.stateLabel.hidden = YES;
}

#pragma mark --setter/getter
- (NSString *)timeStatus
{
    if (!_timeStatus) {
        _timeStatus = @"刚刚";
        [self storeCurrentTimeDate];
    }
    return _timeStatus;
}

- (NSMutableArray *)refreshImages
{
    if (_refreshImages == nil) {
        _refreshImages = [NSMutableArray array];
        for (NSUInteger i = 1; i<15; i++) {
            if (i >9) {
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"0%zd", i]]];
            }else{
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"00%zd", i]]];
            }
            
        }
    }
    return _refreshImages;
}

- (NSMutableArray *)refreshDownImages
{
    if (_refreshDownImages == nil) {
        _refreshDownImages = [NSMutableArray array];
        for (int i = 1; i < 15; i++) {
            if (i >9) {
                [_refreshDownImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"0%d",i]]];
            }else{
                [_refreshDownImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"00%d",i]]];
            }
            
        }
    }
    return _refreshDownImages;
}

@end



@interface FSWCustomRefreshGifAutoFooter()

@property (strong, nonatomic) UILabel *updateStatusLabel;
@property (strong, nonatomic) UIImageView *refreshImageView;

@property (nonatomic,strong) NSMutableArray *refreshImages;/** <刷新动画的图片数组 */

@end

@implementation FSWCustomRefreshGifAutoFooter

- (void)prepare
{
    [super prepare];
    [self configUI];
}

- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
    [super scrollViewContentSizeDidChange:change];
    if(self.scrollView.mj_contentH < self.scrollView.bounds.size.height) {
        if (10086 == self.scrollView.tag) {
            self.mj_y = self.scrollView.mj_contentH;
        }else{
            self.mj_y = self.scrollView.bounds.size.height;
        }
    } else {
        self.mj_y = self.scrollView.mj_contentH;
    }
}

- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    [super scrollViewContentOffsetDidChange:change];
    if ([self.scrollView isKindOfClass:[UITableView class]]) {
        CGPoint oldPoint= [[change objectForKey:@"old"] CGPointValue];
        CGPoint newPoint= [[change objectForKey:@"new"] CGPointValue];
        if (newPoint.y > oldPoint.y) {
            UITableView *tableView = (UITableView *)self.scrollView;
            NSIndexPath *indexPath= [tableView indexPathForRowAtPoint:newPoint];
            NSInteger rowNum= self.scrollView.mj_totalDataCount;
            if (rowNum - 10 == indexPath.row && !tableView.mj_footer.isRefreshing) {
                if (10086 == self.scrollView.tag) {
                    if (![self.updateStatusLabel.text isEqual:@"横向滑动切换其他分类"]) [self executeRefreshingCallback];
                }else{
                    if (![self.updateStatusLabel.text isEqual:@"没有更多了"]) [self executeRefreshingCallback];
                }
            }
        }
    }else if([self.scrollView isKindOfClass:[UICollectionView class]]) {
        CGPoint oldPoint= [[change objectForKey:@"old"] CGPointValue];
        CGPoint newPoint= [[change objectForKey:@"new"] CGPointValue];
        if (newPoint.y > oldPoint.y) {
            UICollectionView *collectionView = (UICollectionView *)self.scrollView;
            NSIndexPath *indexPath= [collectionView indexPathForItemAtPoint:newPoint];
            NSInteger rowNum= self.scrollView.mj_totalDataCount;
            if (rowNum - 10 == indexPath.row && !collectionView.mj_footer.isRefreshing) {
                if (![self.updateStatusLabel.text isEqual:@"没有更多了"]) [self executeRefreshingCallback];
            }
        }
    }
}

- (void)configUI
{
    self.mj_h = 50;
    
    self.updateStatusLabel = [[UILabel alloc] init];
    self.updateStatusLabel.textColor = [UIColor colorWithRed:12/255.0 green:36/255.0 blue:56/255.0 alpha:1];
    self.updateStatusLabel.font = [UIFont fontWithName:@"Heiti SC" size:14];
    self.updateStatusLabel.textAlignment = NSTextAlignmentCenter;
    self.updateStatusLabel.numberOfLines = 2;
    [self addSubview:self.updateStatusLabel];
    
    self.refreshImageView = [[UIImageView alloc] init];
    self.refreshImageView.image = [UIImage imageNamed:@"001"];
    self.refreshImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.refreshImageView.animationImages = self.refreshImages;
    self.refreshImageView.animationDuration = 1;
    self.refreshImageView.animationRepeatCount = 100000;
    [self addSubview:self.refreshImageView];
}

- (void)placeSubviews
{
    [super placeSubviews];
    self.updateStatusLabel.frame = CGRectMake(self.bounds.size.width / 2 - 100, 0, 200, self.mj_h);
    self.refreshImageView.frame = CGRectMake(self.bounds.size.width / 2 - self.mj_h - 75, 0, self.mj_h + 10, self.mj_h - 10);
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState;
    switch (state) {
        case MJRefreshStateIdle:{
            self.refreshImageView.image = [UIImage imageNamed:@"001"];
            [self.refreshImageView stopAnimating];
            self.updateStatusLabel.text = @"上拉加载更多";
            break;
        }
        case MJRefreshStateNoMoreData:{
            [self.refreshImageView stopAnimating];
            self.refreshImageView.image = [UIImage imageNamed:@"001"];
            if ([self.scrollView isKindOfClass:[UITableView class]] || [self.scrollView isKindOfClass:[UICollectionView class]]) {
                if (10086 == self.scrollView.tag) {
                    self.updateStatusLabel.text = @"横向滑动切换其他分类";
                }else if (10001 == self.scrollView.tag){
                    self.updateStatusLabel.text = @"001";//@"~~我是有底线的~~";
                    self.updateStatusLabel.textColor = XCMainColor;
                }else{
                    self.updateStatusLabel.text = @"没有更多了";
                }
            }
            break;
        }
        case MJRefreshStateRefreshing:{
            self.updateStatusLabel.text = @"正在加载更多的数据";
            [self.refreshImageView startAnimating];
            break;
        }
        default:
            break;
    }
}

#pragma mark --setter/getter
- (NSMutableArray *)refreshImages
{
    if (_refreshImages == nil) {
        _refreshImages = [NSMutableArray array];
        for (int i = 1; i < 15; i++) {
            if (i >9) {
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"0%d",i]]];
            }else{
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"00%d",i]]];
            }
        }
    }
    return _refreshImages;
}

@end

@interface FSWCustomRefreshGifBackFooter()

@property (strong, nonatomic) UILabel *updateStatusLabel;
@property (strong, nonatomic) UIImageView *refreshImageView;

@property (nonatomic,strong) NSMutableArray *refreshImages;/** <刷新动画的图片数组 */

@end

@implementation FSWCustomRefreshGifBackFooter

- (void)prepare {
    [super prepare];
    [self configUI];
}

- (void)configUI
{
    self.mj_h = 50;
    
    self.updateStatusLabel = [[UILabel alloc] init];
    self.updateStatusLabel.textColor = [UIColor colorWithRed:12/255.0 green:36/255.0 blue:56/255.0 alpha:1];
    self.updateStatusLabel.font = [UIFont fontWithName:@"Heiti SC" size:14];
    self.updateStatusLabel.textAlignment = NSTextAlignmentCenter;
    self.updateStatusLabel.numberOfLines = 2;
    [self addSubview:self.updateStatusLabel];
    
    self.refreshImageView = [[UIImageView alloc] init];
    self.refreshImageView.image = [UIImage imageNamed:@"001"];
    self.refreshImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.refreshImageView.animationImages = self.refreshImages;
    self.refreshImageView.animationDuration = 1;
    self.refreshImageView.animationRepeatCount = 100000;
    [self addSubview:self.refreshImageView];
}

- (void)placeSubviews
{
    [super placeSubviews];
    self.updateStatusLabel.frame = CGRectMake(self.bounds.size.width / 2 - 65, 0, 130, self.mj_h);
    self.refreshImageView.frame = CGRectMake(self.updateStatusLabel.mj_x-30,self.updateStatusLabel.xc_centerY - 13, 26, 26);
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState;
    switch (state) {
        case MJRefreshStateIdle:{
            self.refreshImageView.image = [UIImage imageNamed:@"001"];
            [self.refreshImageView stopAnimating];
            self.updateStatusLabel.text = @"上拉加载更多";
            break;
        }
        case MJRefreshStateNoMoreData:{
            [self.refreshImageView stopAnimating];
            self.refreshImageView.image = [UIImage imageNamed:@""];
            self.updateStatusLabel.text = @"没有更多了";
            break;
        }
        case MJRefreshStateRefreshing:{
            self.updateStatusLabel.text = @"正在加载更多的数据";
            [self.refreshImageView startAnimating];
            break;
        }
        default:{
            
            break;
        }
    }
}

#pragma mark --setter/getter
- (NSArray *)refreshImages
{
    if (_refreshImages == nil) {
        _refreshImages = [NSMutableArray array];
        for (int i = 1; i < 15; i++) {
            if (i >9) {
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"0%d",i]]];
            }else{
                [_refreshImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"00%d",i]]];
            }
        }
    }
    return _refreshImages;
}

@end

